package net.m510.autosurfer.core;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Logger;

import net.m510.autosurfer.core.utils.AnalyzeUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;


public class FileResponseHandler implements ResponseHandler<File> {
	private final Logger log = Logger.getLogger(FileResponseHandler.class.getName());
//	private String charset;
	private File file;
	
	public FileResponseHandler(File file) {
		this.file = file;
	}
//	public FileResponseHandler(File file, String charset) {
//		this.file = file;
////		this.charset = charset;
//	}
	
	@Override
	public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		HttpEntity entity = response.getEntity();
		// 出力先がディレクトリだった場合、ファイル名の自動生成
		File outFile = null;
		if ( file.isDirectory() ) {
			String filename = AnalyzeUtils.createFileName(response);
			outFile = new File(file,filename);
		} else {
			outFile = file;
		}
		// ファイルに書き込み
		log.info("ファイルに書き込み中 "+outFile.getPath());
		BufferedInputStream in = new BufferedInputStream(entity.getContent());
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
		int buf;
		while ( (buf = in.read()) != -1 ) {
			out.write(buf);
		}
		out.flush();
		out.close();
		EntityUtils.consume(entity);
		log.info("ファイルに書き込み終了");
		return outFile;
	}
//	public String getCharset() {
//		return charset;
//	}
//	public void setCharset(String charset) {
//		this.charset = charset;
//	}
}
